package com.shadow.bus.main;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.shadow.bus.adapter.BusListAdapter;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.config.WorkStatusCode;
import com.shadow.bus.entity.BusInfoEntity;
import com.shadow.bus.entity.StartWorkEvent;
import com.shadow.bus.event.RefreshMainEvent;
import com.shadow.bus.event.StartBrotherEvent;
import com.shadow.bus.main.alarm.AlarmDelegate;
import com.shadow.bus.main.work.complete.WorkCompleteDelegate;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhangyu.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;

/**
 * @author zhangyu
 * @date 2018/7/3
 */

public class TabDelegate extends RxShadowDelegate {
    public static TabDelegate newInstance(ArrayList<BusInfoEntity> busInfos) {
        Bundle arguments = new Bundle();
        arguments.putSerializable("list", busInfos);
        TabDelegate fragment = new TabDelegate();
        fragment.setArguments(arguments);
        return fragment;
    }

    @BindView(R2.id.swipeLayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    @BindView(R2.id.recycler_view)
    RecyclerView mRecyclerView;
    private DialogDelegate mDialogDelegate;
    private List<BusInfoEntity> mInfoEntities;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_maint_tab;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        Bundle bundle = getArguments();
        if (bundle != null) {
            //noinspection unchecked
            mInfoEntities = (List<BusInfoEntity>) bundle.getSerializable("list");
        }
        mSwipeRefreshLayout.setEnabled(false);
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(
                1, StaggeredGridLayoutManager.VERTICAL));
        mRecyclerView.addOnItemTouchListener(new OnItemChildClickListener() {

            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                final BusInfoEntity busInfo = (BusInfoEntity) adapter.getItem(position);
                if (busInfo != null) {
                    switch (busInfo.getWorkStatusCode()) {
                        case WorkStatusCode.UNDER_PLAN:
                            EventBus.getDefault().post(new StartBrotherEvent(AlarmDelegate.newInstance(busInfo.getVehicleId(),
                                busInfo.getVehicleCode())));
                            break;
                        case WorkStatusCode.FINISH_PLAN:
                            ToastUtils.showToast(getContext(), "车辆未进厂!");
                            break;
                        case WorkStatusCode.READY_WORK:
                            mDialogDelegate.showWarningDialog("已进厂", "确认维修?", new DialogDelegate.OnDialogListener() {
                                @Override
                                public void onClick() {
                                    startRepair(busInfo);
                                }
                            });
                            break;
                        case WorkStatusCode.UNDER_WORK:
                            EventBus.getDefault().post(new StartWorkEvent(busInfo.getId(),
                                    busInfo.getVehicleCode()));
                            break;
                        case WorkStatusCode.FINISH_WORK:
                        case WorkStatusCode.COMPLETE_WORK:
                            EventBus.getDefault().post(new StartBrotherEvent(WorkCompleteDelegate.newInstance(
                                    busInfo.getVehicleCode(), busInfo.getId())));
                            break;
                    }
                }
            }
        });
        BusListAdapter busListAdapter = new BusListAdapter(getContext(),
                R.layout.item_bus_info, mInfoEntities);
        mRecyclerView.setAdapter(busListAdapter);
    }

    private void startRepair(final BusInfoEntity entity) {
        mDialogDelegate.changeToProgressType("正在提交...");
        PostParams postParams = new PostParams();
        postParams.setId(entity.getId());
        RxRestClient.builder().url(ServiceUrl.START_REPAIR)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("repairInfo", JSON.toJSONString(postParams))
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mDialogDelegate.stopProgressWithSuccess("提交成功",
                                "您可以开始维修该车辆了", new DialogDelegate.OnDialogListener() {
                                    @Override
                                    public void onClick() {
                                        mDialogDelegate.clearDialog();
                                        EventBus.getDefault().post(new StartWorkEvent(entity.getId(),
                                                entity.getVehicleCode()));
                                        EventBus.getDefault().post(new RefreshMainEvent());
                                    }
                                });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogDelegate.stopProgressWithFailed("提交失败!", msg);
                    }
                })
                .build()
                .get();
    }

    private class PostParams {

        private long Id;
        private String ActualStartTime;

        public long getId() {
            return Id;
        }

        public void setId(long id) {
            Id = id;
        }

        public String getActualStartTime() {
            return ActualStartTime;
        }

        public void setActualStartTime(String actualStartTime) {
            ActualStartTime = actualStartTime;
        }
    }
}
